<template>
  <div class="bg-white rounded-2xl shadow-sm p-8">
    <div class="mb-8 flex justify-between items-center">
      <div>
        <h1 class="text-2xl font-bold text-gray-900 mb-2">个人信息</h1>
        <p class="text-gray-500">完善个人信息，提升账号安全性</p>
      </div>
      <button v-if="!isEditing" @click="isEditing = true" class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">编辑信息</button>
      <div v-else class="flex gap-3">
        <button @click="cancelEdit" class="px-6 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors">取消</button>
        <button @click="saveEdit" class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">保存修改</button>
      </div>
    </div>



    <div class="mb-8">
      <h2 class="text-lg font-semibold text-gray-900 mb-6">基本信息</h2>
      <div class="grid grid-cols-2 gap-6">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">姓名</label>
          <input v-model="userInfo.name" :disabled="!isEditing" type="text" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" :class="{'bg-gray-50': !isEditing}" />
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">学号</label>
          <input v-model="userInfo.studentId" :disabled="!isEditing" type="text" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" :class="{'bg-gray-50': !isEditing}" />
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">学院</label>
          <input v-model="userInfo.college" :disabled="!isEditing" type="text" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" :class="{'bg-gray-50': !isEditing}" />
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">专业</label>
          <input v-model="userInfo.major" :disabled="!isEditing" type="text" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" :class="{'bg-gray-50': !isEditing}" />
        </div>
      </div>
    </div>

    <div class="mb-8">
      <h2 class="text-lg font-semibold text-gray-900 mb-6">联系方式</h2>
      <div class="grid grid-cols-2 gap-6">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">手机号</label>
          <input v-model="userInfo.phone" :disabled="!isEditing" type="text" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" :class="{'bg-gray-50': !isEditing}" />
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">邮箱</label>
          <input v-model="userInfo.email" :disabled="!isEditing" type="email" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" :class="{'bg-gray-50': !isEditing}" />
        </div>
      </div>
    </div>

    <div class="mb-8">
      <h2 class="text-lg font-semibold text-gray-900 mb-6">宿舍信息</h2>
      <div class="grid grid-cols-2 gap-6">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">宿舍楼</label>
          <input v-model="userInfo.dormBuilding" :disabled="!isEditing" type="text" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" :class="{'bg-gray-50': !isEditing}" />
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">宿舍号</label>
          <input v-model="userInfo.dormRoom" :disabled="!isEditing" type="text" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" :class="{'bg-gray-50': !isEditing}" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: 'OrderProfileInfo',
  data() {
    return {
      isEditing: false,
      userInfo: {
          name: '',
          studentId: '',
          college: '',
          major: '',
          phone: '',
          email: '',
          dormBuilding: '',
          dormRoom: ''
        },
      originalUserInfo: {}

    }
  },
  methods: {
    cancelEdit() {
      this.isEditing = false
      this.userInfo = { ...this.originalUserInfo }
    },
    
    async saveEdit() {
      const userId = localStorage.getItem('userId')
      if (!userId) {
        alert('未登录，请先登录')
        this.$router.push('/login')
        return
      }

      // 构建更新数据（只包含有值的字段）
      const updateData = {}
      
      if (this.userInfo.phone) updateData.phone = this.userInfo.phone
      if (this.userInfo.email) updateData.email = this.userInfo.email
      if (this.userInfo.name) updateData.nickname = this.userInfo.name
      

      
      if (this.userInfo.college) updateData.college = this.userInfo.college
      if (this.userInfo.major) updateData.major = this.userInfo.major
      if (this.userInfo.studentId) updateData.student_id = this.userInfo.studentId
      if (this.userInfo.dormBuilding) updateData.dorm_building = this.userInfo.dormBuilding
      if (this.userInfo.dormRoom) updateData.dorm_room = this.userInfo.dormRoom

      try {
        console.log('正在保存用户资料...', Object.keys(updateData))
        
        const response = await axios.put(`/api/users/profile/${userId}`, updateData)
        
        if (response.data && response.data.success) {
          // 保存成功，更新原始数据
          this.originalUserInfo = { ...this.userInfo }
          
          this.isEditing = false
          
          // 立即触发更新事件，通知父组件
          const updateEvent = new CustomEvent('order-profile-updated', { 
            detail: {
              nickname: this.userInfo.name || this.userInfo.nickname,
              phone: this.userInfo.phone,
              email: this.userInfo.email
            }
          })
          window.dispatchEvent(updateEvent)
          console.log('✅ 已发送更新事件')
          

          
          alert('信息保存成功！')
        } else {
          throw new Error(response.data?.message || '保存失败')
        }
      } catch (e) {
        console.error('❌ 保存失败', e)
        const errorMsg = e.response?.data?.message || e.message || '保存失败，请稍后再试'
        alert(errorMsg)
      }
    },
    async loadProfile() {
      const userId = localStorage.getItem('userId')
      if (!userId) {
        console.warn('未找到userId，无法加载资料')
        return
      }
      
      try {
        const { data } = await axios.get(`/api/users/profile/${userId}`)
        const root = (data && data.data) || {}
        const u = root.user || {}
        const ou = root.order_user || {}

        // 将后端字段映射到表单（users 表）
        this.userInfo.name = u.nickname || ''
        this.userInfo.phone = u.phone || ''
        this.userInfo.email = u.email || ''

        // 将下单者扩展信息映射到表单（order_users 表）
        this.userInfo.college = ou.college || ''
        this.userInfo.major = ou.major || ''
        this.userInfo.studentId = ou.student_id || ''
        this.userInfo.dormBuilding = ou.dorm_building || ''
        this.userInfo.dormRoom = ou.dorm_room || ''
        
        this.originalUserInfo = { ...this.userInfo }
        console.log('✅ 用户资料加载完成', {
          nickname: this.userInfo.name,
          hasAvatar: !!this.userInfo.avatarUrl
        })
      } catch (e) {
        console.error('❌ 加载用户资料失败:', e)

      }
    }
  },
  mounted() {
    this.loadProfile()
  }
}
</script>


